import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QDialog,
    QLineEdit,
    QPushButton,
    QMessageBox,
    QListWidget,
    QListWidgetItem,
)

from apscheduler.schedulers.background import BackgroundScheduler


class Task:
    def __init__(self, name, interval):
        self.name = name
        self.interval = interval
        self.log = ""

    def execute(self):
        # 执行任务，并将输出日志保存到self.log中
        self.log = f"任务 {self.name} 执行成功"


class LogViewer(QDialog):
    def __init__(self, task):
        super().__init__()
        self.setWindowTitle("任务详情")
        self.layout = QVBoxLayout()
        self.name_label = QLabel(f"任务名称：{task.name}")
        self.interval_label = QLabel(f"执行周期：{task.interval}")
        self.log_label = QLabel(f"执行日志：{task.log}")
        self.layout.addWidget(self.name_label)
        self.layout.addWidget(self.interval_label)
        self.layout.addWidget(self.log_label)
        self.setLayout(self.layout)


class TaskWindow(QDialog):
    def __init__(self, task_list: QListWidget):
        super().__init__()
        self.task_list_widget = task_list
        self.setWindowTitle("添加任务")
        self.layout = QVBoxLayout()
        self.name_label = QLabel("任务名称")
        self.interval_label = QLabel("执行周期")
        self.name_input = QLineEdit()
        self.interval_input = QLineEdit()
        self.button_layout = QHBoxLayout()
        self.button = QPushButton("添加任务")
        self.button.clicked.connect(self.add_task)
        self.button_layout.addWidget(self.button)
        self.layout.addWidget(self.name_label)
        self.layout.addWidget(self.name_input)
        self.layout.addWidget(self.interval_label)
        self.layout.addWidget(self.interval_input)
        self.layout.addLayout(self.button_layout)
        self.setLayout(self.layout)

    def add_task(self):
        # import pdb
        # pdb.set_trace()
        name = self.name_input.text()
        interval = self.interval_input.text()
        # 创建任务对象，并将其添加到任务列表中
        task = Task(name, interval)
        tasks.append(task)
        self.task_list_widget.addItem(task.name)
        self.close()


class TaskListWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("任务列表")
        self.layout = QVBoxLayout()
        self.task_list_widget = QListWidget()
        self.task_list_widget.itemDoubleClicked.connect(self.show_log)
        self.button_layout = QHBoxLayout()
        self.delete_button = QPushButton("删除任务")
        self.delete_button.clicked.connect(self.delete_task)
        self.detail_button = QPushButton("任务详情")
        self.detail_button.clicked.connect(self.show_task_detail)
        self.button_layout.addWidget(self.delete_button)
        self.button_layout.addWidget(self.detail_button)
        self.layout.addWidget(self.task_list_widget)
        self.layout.addLayout(self.button_layout)
        self.setLayout(self.layout)

    def update_task_list(self):
        self.task_list_widget.clear()
        for task in tasks:
            self.task_list_widget.addItem(task.name)

    def delete_task(self):
        selected_items = self.task_list_widget.selectedItems()
        if len(selected_items) > 0:
            confirm = QMessageBox.question(
                self, "确认删除", "确定要删除选中的任务吗？", QMessageBox.Yes | QMessageBox.No
            )
            if confirm == QMessageBox.Yes:
                for item in selected_items:
                    task_name = item.text()
                    for task in tasks:
                        if task.name == task_name:
                            tasks.remove(task)
                            break
                self.update_task_list()

    def show_task_detail(self):
        selected_items = self.task_list_widget.selectedItems()
        for item in selected_items:
            task_name = item.text()
            for task in tasks:
                if task.name == task_name:
                    log_viewer = LogViewer(task)
                    log_viewer.exec_()

    def show_log(self, item):
        task_name = item.text()
        for task in tasks:
            if task.name == task_name:
                log_viewer = LogViewer(task)
                log_viewer.exec_()


class TaskWorker(QThread):
    log_signal = pyqtSignal(str)

    def __init__(self, task):
        super().__init__()
        self.task = task

    def run(self):
        self.task.execute()
        self.log_signal.emit(self.task.log)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 初始化任务列表和调度器
    tasks = []
    scheduler = BackgroundScheduler()

    # 创建主窗口和布局
    main_window = QMainWindow()
    central_widget = QWidget()
    layout = QVBoxLayout()
    main_window.setCentralWidget(central_widget)
    central_widget.setLayout(layout)

    # 创建任务列表窗口并添加到布局中
    task_list_window = TaskListWindow()
    layout.addWidget(task_list_window)

    # 创建添加任务按钮并添加到布局中
    add_button = QPushButton("新增任务")
    add_button.clicked.connect(lambda: TaskWindow(task_list_window.task_list_widget).exec_())
    layout.addWidget(add_button)

    # 创建任务执行线程，并在任务执行完毕后更新任务列表和展示日志
    def execute_task(task):
        worker = TaskWorker(task)
        worker.log_signal.connect(lambda log: task.log == log)
        worker.finished.connect(task_list_window.update_task_list)
        worker.finished.connect(lambda: task_list_window.show_log(task))
        worker.start()

    # 启动调度器
    scheduler.start()

    main_window.show()
    sys.exit(app.exec_())
